﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Umbrella.Whs.Contracts;

namespace Umbrella.Whs.Service
{
    public sealed class WorkflowStatusManager
    {

        #region instance

        public static WorkflowStatusManager Instance
        {
            get; private set;
        }

        static WorkflowStatusManager()
        {
            Instance = new WorkflowStatusManager();
        }

        #endregion

        private readonly log4net.ILog _log = log4net.LogManager.GetLogger(typeof(WorkflowStatusManager));
        private readonly Dictionary<Guid, WorkflowStatus> _status = new Dictionary<Guid, WorkflowStatus>();

        public void SetStatus(Guid wflId, string msg)
        {
            if (wflId == Guid.Empty)
                throw new ArgumentException("Guid is invalid/empty", "wflId");

            if (string.IsNullOrEmpty(msg))
                throw new ArgumentException("null or empty", "msg");

            // save status
            _status[wflId] = new WorkflowStatus()
            {
                Message = msg,
                HasProgress = false,
            };
        }

        public void SetStatus(Guid wflId, string msg, float progress)
        {
            if (wflId == Guid.Empty)
                throw new ArgumentException("Guid is invalid/empty", "wflId");

            if (string.IsNullOrEmpty(msg))
                throw new ArgumentException("null or empty", "msg");

            // save status
            _status[wflId] = new WorkflowStatus()
            {
                Message = msg,
                HasProgress = true,
                Progress = Math.Min(1.0f, Math.Max(0.0f, progress)),
            };
        }

        public void ClearStatus(Guid wflId)
        {
            if (wflId == Guid.Empty)
                throw new ArgumentException("Guid is invalid/empty", "wflId");

            _status.Remove(wflId);
        }

        public WorkflowStatus GetStatus(Guid wflId)
        {
            if (wflId == Guid.Empty)
                throw new ArgumentException("Guid is invalid/empty", "wflId");

            WorkflowStatus r;

            if (!_status.TryGetValue(wflId, out r))
                return null;

            return r;
        }

        private WorkflowStatusManager()
        {
            
        }
    }
}
